﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.Linq;
using System.Text;
using ReflectionStudio.Core.Events;
namespace WPFExcelReport
{

    public class WGGINVData : BaseFunction
    {
        public bool flagRegenerateLastMonthData;
        ArrayList ListTris = new ArrayList();
        string TrisInclude = "";
        string InvDate;
        string LASTINVDATE;
        ArrayList ListWBInventory;
        public int ThreadCount;
        private string OrderNum;
        DataSet setWBDATINV = new DataSet();
        DataTable tbWBDATINV;
        string fileWBDATINV = @"C:\intex.w\Report\Warehouse\WBDATINV.xml";
        public WGGINVData()
            : base()
        {
            ListWBInventory = new ArrayList();
            BuildTrisList();
            tbWBDATINV = new DataTable("WBDATINV");
            tbWBDATINV.Columns.Add("INVDATE", typeof(string));
            tbWBDATINV.Columns.Add("WBBLO", typeof(string));
            tbWBDATINV.Columns.Add("ARTICLE", typeof(string));
            tbWBDATINV.Columns.Add("WBBDPART", typeof(string));
            tbWBDATINV.Columns.Add("INVPCNUM", typeof(int));
            tbWBDATINV.Columns.Add("INVQTYMTR", typeof(double));
            setWBDATINV.Merge(tbWBDATINV);
        }
        public WGGINVData(Dictionary<string, object> DicGlobalPara)
            : base(DicGlobalPara)
        {
            ListWBInventory = new ArrayList();
            BuildTrisList();
        }
        private void BuildTrisList()
        {
            ListTris = new ArrayList();
            TrisType tristype = null;
            TrisInclude = "01;10;11;12;36;13;26;27;31;32;40;41;42;43;";
            tristype = new TrisType("01", "+", "净长"); ListTris.Add(tristype);
            tristype = new TrisType("10", "+", "货物收入"); ListTris.Add(tristype);
            tristype = new TrisType("11", "+", "货物收入"); ListTris.Add(tristype);
            tristype = new TrisType("12", "-", "销售返回"); ListTris.Add(tristype);
            tristype = new TrisType("13", "+", "产品汇报录入"); ListTris.Add(tristype);
            tristype = new TrisType("20", "-", "货物发出"); ListTris.Add(tristype);
            tristype = new TrisType("21", "+", "货物进入"); ListTris.Add(tristype);
            tristype = new TrisType("26", "-", "旧布卷减少"); ListTris.Add(tristype);
            tristype = new TrisType("27", "+", "新布卷增加"); ListTris.Add(tristype);
            tristype = new TrisType("31", "-", "发货"); ListTris.Add(tristype);
            tristype = new TrisType("32", "+", "退货"); ListTris.Add(tristype);
            tristype = new TrisType("36", "-", "生产消耗"); ListTris.Add(tristype);
            tristype = new TrisType("40", "-", "等级修改减少"); ListTris.Add(tristype);
            tristype = new TrisType("41", "-", "等级修改增加"); ListTris.Add(tristype);
            tristype = new TrisType("42", "+", "库存修正减少"); ListTris.Add(tristype);
            tristype = new TrisType("43", "+", "库存修正增加"); ListTris.Add(tristype);
            tristype = new TrisType("48", "-", "生产差异-"); ListTris.Add(tristype);
            tristype = new TrisType("49", "+", "生产差异+"); ListTris.Add(tristype);
            tristype = new TrisType("51", "+", "消耗差异"); ListTris.Add(tristype);
            tristype = new TrisType("61", "-", "留位"); ListTris.Add(tristype);
            tristype = new TrisType("62", "+", "取消留位"); ListTris.Add(tristype);
            tristype = new TrisType("64", "+", "留位剪布"); ListTris.Add(tristype);
            tristype = new TrisType("65", "+", "锁定"); ListTris.Add(tristype);
            tristype = new TrisType("66", "+", "解锁"); ListTris.Add(tristype);
            tristype = new TrisType("69", "+", "其他修正"); ListTris.Add(tristype);
            tristype = new TrisType("80", "+", "发票数量"); ListTris.Add(tristype);
            tristype = new TrisType("88", "-", "价值更改-"); ListTris.Add(tristype);
            tristype = new TrisType("89", "+", "价值更改"); ListTris.Add(tristype);
            tristype = new TrisType("IN", "+", "系统自动调节"); ListTris.Add(tristype);

        }
        public DataSet GetRawData(DataRow dwABPOS)
        {
            DataSet set4Return = new DataSet();
            DataSet setLocal = new DataSet();
            DataSet setResult = new DataSet();
            DataSet setTemp = new DataSet();
            DataTable tableLocal = null;
            string VKPAUFNUM;
            string WBSRTDATE, WBENTDATE;
            WBSRTDATE = dwABPOS["WBSRTDATE"].ToString().Trim();
            WBENTDATE = dwABPOS["WBENTDATE"].ToString().Trim();
            try
            {
                OracleCommand or1 = OracleDB.CreateCommand();
                #region
                /*
                 SELECT TRIM(WBEWART)||'-'||TRIM(WBEWFARBE)||'-'||TRIM(WBEWVAR) AS ARTICLE,WBEWBUCHDAT,WBEWBS,WBBDPART, COUNT(WBEWLFDNR)AS PCNUM,WBEWLO,WBEWLB,SUM(WBEWMTR)AS WBEWMTR,0 as STARTQTY,0 as ENDQTY,0 as STARTPCNUM,0 as ENDPCNUM FROM WBBEW W JOIN WBBST B ON WBEWSTKNR=WBBSTKNR WHERE WBEWWAKZ='R' AND WBEWBUCHDAT>'20110401' AND WBEWBUCHDAT<'20110501' GROUP BY WBEWLO,WBEWLB,WBEWART,WBEWFARBE,WBEWVAR,WBEWBUCHDAT,WBEWBS,WBBDPART ORDER BY WBEWBUCHDAT,ARTICLE
                 WBEWLB
                 022002-3-A1
                 */
                or1.CommandText = "SELECT TRIM(WBEWART)||'-'||TRIM(WBEWFARBE)||'-'||TRIM(WBEWVAR) AS ARTICLE"
                    + ",WBEWBUCHDAT,WBEWBS,' ' AS FUNCTION,WBBDPART, COUNT(WBEWSTKNR)AS PCNUM,WBEWLO,"
                    + "SUM(WBEWMTR)*0.001 AS WBEWMTR,0 AS STARTQTY,0 AS ENDQTY,0 AS STARTPCNUM,0 AS ENDPCNUM"
                    + ",MAX(WBEWBELEG) AS WBEWBELEG"
                    + " FROM WBBEW W JOIN WBBST B ON WBEWSTKNR=WBBSTKNR"
                    + " WHERE WBEWWAKZ='R' AND WBEWBUCHDAT>='" + WBSRTDATE + "' AND WBEWBUCHDAT<='" + WBENTDATE + "'"
                    //+ " AND WBBART LIKE '022002%' AND WBBVAR='A1' AND WBBDPART LIKE '04100%'"
                    + " GROUP BY WBEWLO,WBEWART,WBEWFARBE,WBEWVAR,WBEWBUCHDAT,WBEWBS,WBBDPART"
                    + " ORDER BY ARTICLE,WBEWBUCHDAT, WBEWBELEG"
                    ;
                #endregion
                setLocal = Connect2Proxy(or1);
                if (setLocal.Tables.Count > 0)
                {
                    tableLocal = setLocal.Tables[0];
                    tableLocal.TableName = "WBBEW";
                    SetDefault(tableLocal);
                    byte[] b;
                    string value;
                    string GISSUEDATE = "", sGISSUEDATE;
                    decimal GMETER = 0, sGMETER;
                    decimal GPCNUM = 0, sGPCNUM;
                    string sTemp = "";
                    string SIZEBATCHNO = "";
                    string VKPWUTERM = "";
                    int Year, Month, Day;
                    string Column = "";
                    double VKPMENGE1 = 0, FACTLENG = 0, FinishedLength = 0;
                    string ARTICLE = "";
                    double InitialQty = 0;
                    double Qty = 0;
                    double balance = 0;
                    foreach (DataRow dwTemp in tableLocal.Rows)
                    {
                        Column = "ARTICLE";
                        #region
                        b = Encoding.GetEncoding("ISO-8859-1").GetBytes(dwTemp[Column].ToString().Trim());
                        value = Encoding.GetEncoding("gb2312").GetString(b);
                        dwTemp[Column] = value;
                        #endregion
                        Column = "WBBDPART";
                        #region
                        b = Encoding.GetEncoding("ISO-8859-1").GetBytes(dwTemp[Column].ToString().Trim());
                        value = Encoding.GetEncoding("gb2312").GetString(b);
                        dwTemp[Column] = value;
                        #endregion
                        BalanceQty(dwTemp);
                    }
                    setLocal.AcceptChanges();
                    set4Return.Merge(setLocal);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return set4Return;
        }
        private void BalanceQty(DataRow dwWBBEW)
        {
            string direction = "+";
            string WBEWBS = dwWBBEW["WBEWBS"].ToString().Trim();
            if (!TrisInclude.Contains(WBEWBS + ";"))
            {
                dwWBBEW.Delete();
                return;
            }
            var queryX = from TrisType tris in ListTris
                         where tris.TrisCode == WBEWBS
                         select tris;
            foreach (TrisType tris in queryX)
            {
                direction = tris.TrisDirect;
                dwWBBEW["FUNCTION"] = tris.Description;
            }
            string ARTICLE = dwWBBEW["ARTICLE"].ToString().Trim();
            string WBBLO = dwWBBEW["WBEWLO"].ToString().Trim();
            string WBBDPART = dwWBBEW["WBBDPART"].ToString().Trim();
            double INVQTYMTR = 0, QtyMTR = 0;
            double balance = 0;
            int INVPCNUM = 0, QtyPCNum = 0;
            WBInventory wbInv = null;
            string expression;
            try
            {
                var query1 = from WBInventory wbinv in ListWBInventory
                             where wbinv.INVDATE == LASTINVDATE
                                   && wbinv.Article == ARTICLE
                                   && wbinv.WBBDPART == WBBDPART
                             select wbinv;
                foreach (WBInventory wbinv in query1)
                {
                    wbInv = wbinv;
                }
                if (wbInv == null)
                {
                    wbInv = new WBInventory(LASTINVDATE, WBBLO, ARTICLE, WBBDPART, 0, 0);
                    ListWBInventory.Add(wbInv);
                }
                QtyMTR = System.Math.Round(System.Convert.ToDouble(dwWBBEW["WBEWMTR"].ToString()) * 100 * 0.01, 2);
                QtyPCNum = System.Convert.ToInt16(dwWBBEW["PCNUM"].ToString());
                if (direction == "-")
                {
                    QtyMTR = 0 - QtyMTR;
                    QtyPCNum = 0 - QtyPCNum;
                    dwWBBEW["WBEWMTR"] = QtyMTR;
                    dwWBBEW["PCNUM"] = QtyPCNum;
                }
                dwWBBEW["STARTQTY"] = System.Math.Round(wbInv.lastQtyMtr, 2);
                dwWBBEW["STARTPCNUM"] = wbInv.LastPcNum;
                if (flagRegenerateLastMonthData)
                {
                    wbInv.lastQtyMtr -= QtyMTR;
                    wbInv.LastPcNum -= QtyPCNum;
                }
                else
                {
                    wbInv.lastQtyMtr += QtyMTR;
                    wbInv.LastPcNum += QtyPCNum;
                }
                dwWBBEW["ENDQTY"] = System.Math.Round(wbInv.lastQtyMtr);
                dwWBBEW["ENDPCNUM"] = wbInv.LastPcNum;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void LoadINVQty()
        {
            try
            {
                DataRow dwWBDATINV = null;
                setWBDATINV.Clear();
                DataSet setResult = new DataSet();
                DataTable tableLocal = null;
                if (System.IO.File.Exists(fileWBDATINV))
                {
                    setResult.ReadXml(fileWBDATINV);
           
                     tbWBDATINV = setWBDATINV.Tables["WBDATINV"];
                     if (setResult.Tables.Contains("WBDATINV"))
                     {
                         foreach (DataRow dwTemp in setResult.Tables["WBDATINV"].Rows)
                         {
                             dwWBDATINV = tbWBDATINV.NewRow();
                             dwWBDATINV.ItemArray = dwTemp.ItemArray;
                             tbWBDATINV.Rows.Add(dwWBDATINV);
                         } 
                     }
                }
                if (flagRegenerateLastMonthData)
                {
                    #region ClearCurrentINVDATE data
                    tbWBDATINV = setWBDATINV.Tables["WBDATINV"];
                    if (tbWBDATINV!=null)
                    {
                        var queryX = from DataRow dwTemp in tbWBDATINV.AsEnumerable()
                                     where dwTemp["INVDATE"].ToString() == LASTINVDATE
                                     select dwTemp;
                        List<DataRow> deletedRows = new List<DataRow>();
                        foreach (DataRow dwTemp in queryX)
                        {
                            deletedRows.Add(dwTemp);
                        }
                        foreach (DataRow dwTemp in deletedRows)
                        {
                            dwTemp.Delete();
                        }
                        tbWBDATINV.AcceptChanges();
                    }
                    #endregion
                    #region Get CurrentStock 
                    OracleCommand or1 = OracleDB.CreateCommand();
                    or1.CommandText = "SELECT DISTINCT '" + LASTINVDATE + "' AS INVDATE,WBBLO,TRIM(WBBART)||'-'||TRIM(WBBFARBE)||'-'||TRIM(WBBVAR) AS ARTICLE"
               + ",WBBDPART, COUNT(*)AS INVPCNUM,SUM(WBBSSTKLG)*0.001 AS INVQTYMTR FROM  WBBST B WHERE WBBWAKZ='R'"
                        //+ " AND WBBART LIKE '022002%' AND WBBVAR='A1' AND WBBDPART LIKE '04100%'"
               + "GROUP BY WBBLO,WBBART,WBBFARBE,WBBVAR,WBBDPART ORDER BY ARTICLE";
                  
                    setResult = Connect2Proxy(or1);
                    if (setResult.Tables.Count > 0)
                    {
                        tableLocal = setResult.Tables[0];
                        tableLocal.TableName = "WBDATINV";
                        string Column = "";
                        byte[] b;
                        string value;
   
                        foreach (DataRow dwTemp in tableLocal.Rows)
                        {
                            Column = "ARTICLE";
                            #region
                            b = Encoding.GetEncoding("ISO-8859-1").GetBytes(dwTemp[Column].ToString().Trim());
                            value = Encoding.GetEncoding("gb2312").GetString(b);
                            dwTemp[Column] = value; 
                            #endregion
                            Column = "WBBDPART";
                            #region
                            b = Encoding.GetEncoding("ISO-8859-1").GetBytes(dwTemp[Column].ToString().Trim());
                            value = Encoding.GetEncoding("gb2312").GetString(b);
                            dwTemp[Column] = value;
                            #endregion
                            dwWBDATINV = tbWBDATINV.NewRow();
                            dwWBDATINV.ItemArray = dwTemp.ItemArray;
                            tbWBDATINV.Rows.Add(dwWBDATINV);
                        }
                    }
                    #endregion
                }
                #region Build ListWBInventory            
                if (setWBDATINV.Tables.Contains("WBDATINV"))
                {
                    tbWBDATINV = setWBDATINV.Tables["WBDATINV"];
                    string ARTICLE, WBBDPART, WBBLO;
                    string lastInvDate;
                    WBInventory wbInv;
                    int INVPCNUM;
                    double INVQTYMTR;
                    ListWBInventory = new ArrayList();
                    foreach (DataRow dwTemp in tbWBDATINV.Rows)
                    {
                        ARTICLE = dwTemp["ARTICLE"].ToString();
                        WBBDPART = dwTemp["WBBDPART"].ToString();
                        WBBLO = dwTemp["WBBLO"].ToString();
                        lastInvDate = dwTemp["INVDATE"].ToString();
                        INVQTYMTR = System.Math.Round(System.Convert.ToDouble(dwTemp["INVQTYMTR"].ToString()), 2);
                        INVPCNUM = System.Convert.ToInt16(dwTemp["INVPCNUM"].ToString());
                        wbInv = new WBInventory(lastInvDate, WBBLO, ARTICLE, WBBDPART, INVPCNUM, INVQTYMTR);
                        ListWBInventory.Add(wbInv);
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }
        public void SaveAsInv()
        {
            DataRow dwINV = null;
            dwINV = tbWBDATINV.NewRow();
            bool flagExist = false;
            foreach (WBInventory wbinv in ListWBInventory)
            {
                flagExist = false;
                var query = from DataRow dwInv in tbWBDATINV.AsEnumerable()
                            where dwInv["INVDATE"] == InvDate
                            && dwInv["ARTICLE"] == wbinv.Article
                            && dwInv["WBBLO"] == wbinv.WBBLO
                            && dwInv["WBBDPART"] == wbinv.WBBDPART
                            select dwInv;
                foreach (DataRow dwTemp in query)
                {
                    dwINV = dwTemp;
                    flagExist = true;
                }
                if (!flagExist)
                {
                    dwINV = tbWBDATINV.NewRow();
                }
                dwINV["INVDATE"] = InvDate;
                dwINV["ARTICLE"] = wbinv.Article;
                dwINV["WBBLO"] = wbinv.WBBLO;
                dwINV["WBBDPART"] = wbinv.WBBDPART;
                dwINV["INVPCNUM"] = wbinv.LastPcNum;
                dwINV["INVQTYMTR"] = System.Math.Round(wbinv.lastQtyMtr, 2);
                if (!flagExist)
                {
                    tbWBDATINV.Rows.Add(dwINV);
                }
            }
            if (System.IO.File.Exists(fileWBDATINV))
            {
                System.IO.File.Delete(fileWBDATINV);
            }
            setWBDATINV.WriteXml(fileWBDATINV);
        }
        public void SaveINVQty()
        {
            if (!flagRegenerateLastMonthData)
            {
                return;
            }
            DataRow dwINV = null;

            dwINV = tbWBDATINV.NewRow();
            bool flagExist = false;
            foreach (WBInventory wbinv in ListWBInventory)
            {
                flagExist = false;
                var query = from DataRow dwInv in tbWBDATINV.AsEnumerable()
                            where dwInv["INVDATE"] == wbinv.INVDATE
                            && dwInv["ARTICLE"] == wbinv.Article
                            && dwInv["WBBLO"] == wbinv.WBBLO
                            && dwInv["WBBDPART"] == wbinv.WBBDPART
                            select dwInv;
                foreach (DataRow dwTemp in query)
                {
                    dwINV = dwTemp;
                    flagExist = true;
                }
                if (!flagExist)
                {
                    dwINV = tbWBDATINV.NewRow();
                }
                dwINV["INVDATE"] = wbinv.INVDATE;
                dwINV["ARTICLE"] = wbinv.Article;
                dwINV["WBBLO"] = wbinv.WBBLO;
                dwINV["WBBDPART"] = wbinv.WBBDPART;
                dwINV["INVPCNUM"] = wbinv.LastPcNum;
                dwINV["INVQTYMTR"] = System.Math.Round(wbinv.lastQtyMtr, 2);
                if (!flagExist)
                {
                    tbWBDATINV.Rows.Add(dwINV);
                }
            }
            if (System.IO.File.Exists(fileWBDATINV))
            {
                System.IO.File.Delete(fileWBDATINV);
            }
            setWBDATINV.WriteXml(fileWBDATINV);
        }
        public DataSet BuildWBBST(DataRow dwUI)
        {
            string progress = "查询完成";
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            InvDate = dwUI["INVDATE"].ToString();
            LASTINVDATE = dwUI["LASTINVDATE"].ToString();
            try
            {
                EventDispatcher.Instance.RaiseStatus("查询开始", StatusEventType.StartProgress);

                EventDispatcher.Instance.RaiseStatus("装载结存表", StatusEventType.RunningProgress);
                LoadINVQty();
                tbWBDATINV = setWBDATINV.Tables["WBDATINV"];
                EventDispatcher.Instance.RaiseStatus("装载出入库记录", StatusEventType.RunningProgress);
                setResult = GetRawData(dwUI);
                EventDispatcher.Instance.RaiseStatus("计算结存", StatusEventType.RunningProgress);
                setReturn.Merge(setResult);
                EventDispatcher.Instance.RaiseStatus("保存结存表", StatusEventType.RunningProgress);
                SaveINVQty();
                setReturn.Merge(setWBDATINV);
                EventDispatcher.Instance.RaiseStatus("查询完成", StatusEventType.StopProgress);
            }
            catch (Exception ex)
            {
                Tracer.Error(ABPOS + ex.StackTrace, ex);
            }
            return setReturn;
        }
    }
}